package com.datareport.data.Utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.datareport.data.entity.DisabilityInfoPast;
import com.datareport.data.service.impl.DisabilityInfoPastServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 导入去年表格数据的工具类
 */
@Component
public class DisabilityInfoPastListener extends AnalysisEventListener<DisabilityInfoPast> {
    private static final Logger LOGGER = LoggerFactory.getLogger(DisabilityInfoPastListener.class);
    // 每隔5条存储数据库，实际上可以存储3000条，然后清理List，方便内存回收
    private static final int BATCH_COUNT = 5;
    List<DisabilityInfoPast> list = new ArrayList<>();
    // 实现业务逻辑代码
    private DisabilityInfoPastServiceImpl disabilityInfoPastService;

    public DisabilityInfoPastListener(DisabilityInfoPastServiceImpl disabilityInfoPastService) {
        this.disabilityInfoPastService = disabilityInfoPastService;
    }

    /**
     * 这里每一条数据解析都会来调用
     * @param analysisContext
     */
    @Override
    public void invoke(DisabilityInfoPast disabilityInfoPast, AnalysisContext analysisContext) {
        list.add(disabilityInfoPast);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT){
            saveData();
            // 存储完成后清理list
            list = new ArrayList<>(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了，都会来调用这个方法
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 存储数据库
     */
    private void saveData(){
        disabilityInfoPastService.saveList(list);
    }
}
